//监听文本框事件
$('#text_main_text').bind('input', function () {
    var before = $('#text_main_text').val();
    TextWordCount(2000, "text_main_text");
    setTimeout(function (args) {
        var after = $('#text_main_text').val();
        if (before == after && after.trim() != '') {
            doTextChange();
        }
    }, 2000);

});

//全局的加载层
var layerIndex;

function doTextChange() {

    //加载等待
    layerIndex = layer.load(2, {shade: 0.25});
    var text = $('#text_main_text').val();
    drawWordCloud(text);
    countWordFrequency(text);
    namedEntity(text);
    getAbstract(text, 5);
    getKeywords(text, 5);
    areaInfo(text);
    getSensitiveWords(text);
    getTheme(text);
}

//选项卡切换
var lastClick = $(".div_content_0");

function changeTab(node) {

    var lis = $('#left-side').find('ul').children('li');
    var sameIndex = lis.index(node);
    if (sameIndex == -1) sameIndex = 0;
    for (var i = 0; i < lis.size(); i++) {

        var eachNode = lis[i];
        $(eachNode).removeClass('tab-active');
        $(eachNode).attr('style', '');
        $(eachNode).children(":first").children(":first").attr("style", "");
        $(".div_content_" + i).attr('style', "width: 980px;display:none;")

    }
    //取消特殊的
    $('.word-cloud').attr('style', '');
    node.addClass('tab-active');
    $(node).attr('style', 'color:#333;');
    $('#line').attr('style', 'margin-top:' + ((sameIndex) * 50 + 9) + 'px;');
    $(node).children(":first").children(":first").attr("style", "-webkit-text-fill-color:#e74c3c");

    if (lastClick != undefined) {
        lastClick.fadeOut(1000);
        $(".div_content_" + sameIndex).fadeIn(2000);
        lastClick = $(".div_content_" + sameIndex);
    }

}

initWordClould();

//初始化词云的选项卡
function initWordClould() {
    $(".guidelist li").hover(
        function () {
            $(this).attr("class", "mouseon");
        },
        function () {
            $(this).attr("class", "mouseout");
        }
    );
    $(".ftoollist li").mouseover(function () {
        $(this).siblings().removeClass("on");
        $(this).addClass("on");
        var preNumber = $(this).prevAll().size();
        $(".fimglist li").removeClass("onpre");
        $(".fimglist li:nth-child(" + preNumber + ")").addClass("onpre");
        var margin = 930;
        margin = margin * preNumber;
        margin = margin * -1;
        $(".fimglist").stop().animate({marginLeft: margin + "px"}, {duration: 500});
    });

}


//上传词云图片
layui.use('upload', function () {
    var $ = layui.jquery
        , upload = layui.upload;

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#btn-upload-word-cloud-img'
        , url: discourse_wordcloud_upload_path
        , exts: 'jpg|png|gif|bmp|jpeg'
        , size: '2048'
        , auto: true
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#img-upload-demo1').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status != 0) {
                return layer.msg('上传失败');
            }
            else {
                //上传成功
                layer.msg('图片已上传成功');
                var demoText = $('#demoText');
                demoText.html("<span style=\"color: #FF5722;display: none;\">" + res.data[0].download + "</span> ");
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
});

//词云的异步逻辑

function drawWordCloud(text) {


    //默认生成这几个图片
    // var typeArray = ["CIRCLE", "RECTANGLE", "CAT", "WHALE", "EARTH", "DRAGON", "LOGO", "WECHAT", "CLOUD", "CLOUD_BG"];
    // var typeArray = ["CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE", "CIRCLE"];
    var typeArray = ["CIRCLE", "RECTANGLE", "CAT", "CLOUD", "EARTH", "DRAGON", "WHALE"];
    var j = 0;

    //清空原来所有的图
    $('.fimglist').empty();
    $('.ftoollist').empty();
    //递归调用
    eachImage();

    //递归调用AJAX，保证AJAX请求有序
    function eachImage() {

        if (j >= typeArray.length) {
            return;
        }
        else {

            var requestObj = new Object();
            requestObj.type = typeArray[j];
            requestObj.width = 930;
            requestObj.height = 400;
            requestObj.color = "#ffffff";
            requestObj.font = "MIRCOSOFT YA HEI";
            requestObj.text = text;
            var requestJson = JSON.stringify(requestObj);

            //发送异步请求
            jQuery.ajax({
                url: discourse_wordcloud_path,
                type: "post",
                data: requestJson,
                dataType: "json",
                contentType: "application/json;charset=utf-8"
            }).done(function (data) {
                loadImage(data);
                j++;
                eachImage();
            }).fail(function (data) {
                layer.alert("请求失败", {icon: 7});
                layer.close(layerIndex);
                //递归
                j++;
                eachImage();
            });

            initWordClould();
            layer.close(layerIndex);
        }
    }

}

function loadImage(data) {

    var LargeParentNode = $('.fimglist');
    var SmallPrarentNode = $('.ftoollist');
    LargeParentNode.append(" <li><a href=\"#\" onclick=\"layerView($(this))\"><img src=\"" + data.data.src + "\" title=\"\"></a></li>");
    SmallPrarentNode.append("  <li ><a href=\"#/\"><img src=\"" + data.data.src + "\"><p class=\"imgname\">" + data.data.type + "</p> <p class=\"imgshortcat\">" + data.data.type + "</p></a></li>")

}

//重新生成指定词云
function redrawWordcloud() {

    //加载等待
    layerIndex = layer.load(2, {shade: 0.25});
    var formNode = $('#word-cloud-form');
    var text = $('#text_main_text').val();
    //收集个性化信息
    var width = formNode.find('input[name=\"cloud-width\"]').val();
    var height = formNode.find('input[name=\"cloud-height\"]').val();
    var color = formNode.find('select[name=\"cloud-color\"]').val();
    var bg = formNode.find('select[name=\"cloud-image\"]').val();
    var font = formNode.find('select[name=\"cloud-font\"]').val();
    var image = new Image();
    image.src = $('#img-upload-demo1').attr("src");
    var imagePath = getBase64Image(image);

    if (imagePath != "data:," && bg != "") {
        layer.open({
            title: '提示'
            , content: '您上传了自定义图片，优先使用您上传的图片。'
            , icon: 7
        });
    }

    var requestObj = new Object();
    requestObj.type = bg;
    requestObj.width = width;
    requestObj.height = height;
    requestObj.color = color;
    requestObj.font = font;
    requestObj.text = text;
    requestObj.imagePath = imagePath;
    if (imagePath != "data:,")
        requestObj.type = "CUSTOM";
    var requestJson = JSON.stringify(requestObj);


    //发送异步请求
    jQuery.ajax({
        url: discourse_wordcloud_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        var resStr = '<fieldset class="layui-elem-field"><legend>个性化词云预览</legend> <div class="layui-field-box"><fieldset class="layui-elem-field layui-field-title"><legend>原文本</legend><div class="layui-field-box"><blockquote class="layui-elem-quote  layui-quote-nm gray-p">' + text + '</blockquote></div></fieldset> <fieldset class="layui-elem-field layui-field-title"><legend>图片预览</legend><div class="layui-field-box"></div></fieldset><div class="layui-row"> <div class="layui-col-md12"> <div class="layui-btn-container">'
            + "<img src=" + data.data.src + " style=\"margin-left:auto;margin-right:auto;\" />" +
            '</div></div></div><fieldset class="layui-elem-field layui-field-title"><legend>结果操作</legend><div class="layui-field-box"><div class="layui-btn-container">' +
            '<a href=/' + data.data.src + ' download=' + data.data.fileName + ' class="layui-btn"><i class="layui-icon">&#xe601;</i> 下载文件</a> </div></div><blockquote class="layui-elem-quote gray-p">注:词量太小，图片较大，则词间距稀疏</blockquote></fieldset></div></fieldset>';

        //弹出窗口
        layer.open({
            type: 1,
            title: data.data.fileName + '结果展示',
            shade: 0,
            maxmin: true,
            skin: 'layui-layer-rim', //加上边框
            area: ['840px', '480px'], //宽高
            content: resStr
        });

        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}


/*统计词频的异步逻辑*/
function countWordFrequency(text) {

    var obj = new Object();
    obj.text = text;
    var requestJson = JSON.stringify(obj);

    //发送异步请求
    jQuery.ajax({
        url: discourse_word_frequency_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        allPosBar(data);
    }).fail(function (data) {
        layer.alert("词频统计请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}

/*统计命名实体的异步逻辑*/
function namedEntity(text) {

    var obj = new Object();
    obj.text = text;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_word_named_entity_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        namedEntityForceLayout(data);
    }).fail(function (data) {
        layer.alert("命名实体请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}

/*地域信息标注的异步逻辑*/
function areaInfo(text) {

    var obj = new Object();
    obj.text = text;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_map_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        mapLayout(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("地域信息请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}

/*自动摘要的异步逻辑*/
function getAbstract(text, count) {

    var obj = new Object();
    obj.text = text;
    obj.count = count;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_abstract_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        loadAbstractTable(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("文本摘要信息请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}


/*关键字提取的异步逻辑*/
function getKeywords(text, count) {

    var obj = new Object();
    obj.text = text;
    obj.count = count;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_keywords_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        loadKeyWordsTable(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("文本关键字请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}


/*敏感词会的异步逻辑*/
function getSensitiveWords(text) {

    var obj = new Object();
    obj.text = text;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_sensitive_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        loadSensitiveWords(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}

/*获取相似度的异步逻辑*/
function getSimilarCos(formClassName) {


    var text = $('#text_main_text').val();
    //判断是否为空
    if (text.trim() == '') {
        layer.msg("您还未输入基准文本");
        return;
    }
    var texts = new Array();
    var selecter = "." + formClassName;

    for (var i = 0; i < $(selecter).find('.div_similarity_text').length; i++) {

        var eachText = $(selecter).find('input[name=\'SIMILAR_TEXT\']')[i].value;
        if (eachText.trim() != '') {
            var tobj = new Object();
            tobj.text = eachText;
            texts.push(tobj);
        }
        else
            continue;

    }
    var obj = new Object();
    obj.base = text;
    obj.texts = texts;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_similarity_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        loadsimilarCompareBar(data);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });


}

/*获取主题的异步逻辑*/
function getTheme(text) {
    var obj = new Object();
    obj.text = text;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_theme_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        loadtheme(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });
}

/**
 * 按数量刷新关键字
 */
function reflashKeywords() {
    layerIndex = layer.load(2);
    var text = $('#text_main_text').val();
    var count = $('#input_keywords_count').val();
    if (count.trim() == '') {
        layer.msg('内容不能空的时候提取。');
        return;
    }
    if (text.trim() == '') {
        layer.msg('内容不能空的时候提取。');
        return;
    }
    var IntCount = parseInt(count);
    getKeywords(text, IntCount);

}

/**
 * 将关键字加载到表格展示
 * @param data
 */
function loadKeyWordsTable(data) {

    var dataSource = data.data;
    var resArr = new Array();
    for (var i = 0; i < dataSource.length; i++) {
        var obj = new Object();
        obj.id = (i + 1);
        obj.keyword = dataSource[i];
        resArr.push(obj);
    }
    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#table_keywords'
            , cellMinWidth: 50 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[ //标题栏
                {field: 'id', title: 'ID', sort: true, align: 'center', minWidth: 50}
                , {field: 'keyword', title: '关键字', minWidth: 400}
            ]]
            , data: resArr
            , skin: 'line' //表格风格
            , even: true
            , page: true //是否显示分页
            , limit: 10 //每页默认显示的数量
        });
    });

}


/**
 * 按数量刷新摘要条数
 */
function reflashAbstract() {
    layerIndex = layer.load(2);
    var text = $('#text_main_text').val();
    var count = $('#input_abstract_count').val();
    if (count.trim() == '') {
        layer.msg('内容不能空的时候提取。');
        return;
    }
    if (text.trim() == '') {
        layer.msg('内容不能空的时候提取。');
        return;
    }
    var IntCount = parseInt(count);
    getAbstract(text, IntCount);

}

/**
 * 将摘要加载到表格展示
 * @param data
 */
function loadAbstractTable(data) {

    var dataSource = data.data;
    var resArr = new Array();
    for (var i = 0; i < dataSource.length; i++) {
        var obj = new Object();
        obj.id = (i + 1);
        obj.keyword = dataSource[i];
        resArr.push(obj);
    }
    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#table_abstract'
            , cellMinWidth: 50 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[ //标题栏
                {field: 'id', title: 'ID', sort: true, align: 'center', minWidth: 50}
                , {field: 'keyword', title: '关键字', minWidth: 400}
            ]]
            , data: resArr
            , skin: 'line' //表格风格
            , even: true
            , page: true //是否显示分页
            , limit: 10 //每页默认显示的数量
        });
    });

}

/**
 * 载入敏感词到前台
 * @param data
 */
function loadSensitiveWords(data) {

    var res = data.data;
    var words = res.words;
    var wordsContainer = $('#div_sensitive_words');
    var afterFilter = $('#div_sensitive_words_after_filter');
    wordsContainer.empty();
    afterFilter.empty();

    for (var i = 0; i < words.length; i++) {
        wordsContainer.append("  <div class=\"layui-btn layui-btn-danger\">" + words[i] + "</div>");
    }

    afterFilter.append("<blockquote class=\"layui-elem-quote layui-quote-nm\">" + res.replace + "</blockquote>")
}


/**
 * 增加相似度对比的文本
 * @param formClassName
 */
function addSimilarCompareInput(formClassName) {

    var selecter = "." + formClassName;
    if ($(selecter).find('.div_similarity_text').length == 4) {
        layer.msg("4个够演示就好啦，别点了求求你");
        return;
    }

    var textGroup = $('.' + formClassName).find('.div_similarity_text').parent();

    textGroup.append("<div class=\"layui-form-item div_similarity_text\">" +
        "<label class=\"layui-form-label\">对比文本</label>" +
        "	<div class=\"layui-input-inline\" style=\"width: 72%\">" +
        "		<input type=\"text\" name=\"SIMILAR_TEXT\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"在这里输入您需要分析的文本，若要多段文本，请点击下面的添加按钮\" class=\"layui-input\" /></div>" +
        "	<div class=\"layui-input-inline\" style=\"width: 120px\">" +
        "		<div class=\"layui-btn-group\">" +
        "			<button type='button' class=\"layui-btn\" onclick='addSimilarCompareInput(\"" + formClassName + "\")'>" +
        "				<i class=\"layui-icon\">&#xe654;</i></button>" +
        "			<button type='button' class=\"layui-btn layui-btn-warm layui-btn\" onclick='deleteSimilarCompareInput(\"" + formClassName + "\",$(this))'>" +
        "				<i class=\"layui-icon\">&#xe640;</i></button>" +
        "		</div>" +
        "	</div>" +
        "</div>");

    layui.form.render();
    layui.element.init();

}


/**
 * 删除相似度对比的文本
 * @param formClassName
 * @param node
 */
function deleteSimilarCompareInput(formClassName, node) {


    if ($('.' + formClassName).find('.div_similarity_text').length == 1) {
        layer.msg("你删了这最后1个我怎么演示啊？");
        return;
    }
    node.parent().parent().parent().remove();
    layui.form.render();
    layui.element.init();
}


/**
 * 基于贝叶斯分类器的情感识别
 */

var emotion_model_tag;

function emotion() {

    var tag = emotion_model_tag;

    var text = $('#text_main_text').val();
    var obj = new Object();
    var texts = new Array();
    var tObj = new Object();
    tObj.text = text;
    texts.push(tObj);
    obj.tag = tag;
    obj.texts = texts;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_emotion_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        loadEmotionGraph(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}


/**
 * 增加贝叶斯分类的语料
 * @param formClassName
 */
function addBayesInput(formClassName) {

    var selecter = "." + formClassName;
    if ($(selecter).find('.div_bayes_text').length == 4) {
        layer.msg("4个够演示就好啦，别点了");
        return;
    }

    var textGroup = $('.' + formClassName).find('.div_bayes_text').parent();

    textGroup.append('   <div class="layui-form-item div_bayes_text">' +
        '                        <label class="layui-form-label">类别名</label>' +
        '                        <div class="layui-input-inline" style="width: 100px;">' +
        '                            <input type="text" name="typeName" lay-verify="required" placeholder="必需"' +
        '                                   autocomplete="off" class="layui-input">' +
        '                        </div>' +
        '                        <label class="layui-form-label">训练语料</label>' +
        '                        <div class="layui-input-inline" style="width: 49%">' +
        '                            <input type="text" name="SIMILAR_TEXT" lay-verify="title"' +
        '                                   autocomplete="off"' +
        '                                   placeholder="以【 ||| 】分割每份语料"' +
        '                                   class="layui-input"/>' +
        '                        </div>' +
        '                        <div class="layui-input-inline" style="width: 120px">' +
        '                            <div class="layui-btn-group">' +
        '                                <button type=\'button\' id="btn_add_onlyone"' +
        '                                        class="layui-btn layui-btn"' +
        '                                        onclick=\'addBayesInput("form_bayes")\'>' +
        '                                    <i class="layui-icon">&#xe654;</i>' +
        '                                </button>' +
        '                                <button type=\'button\' id="btn_delete_onlyone"' +
        '                                        class="layui-btn layui-btn-warm layui-btn"' +
        '                                        onclick=\'deleteBayesInput("form_bayes",$(this))\'>' +
        '                                    <i class="layui-icon">&#xe640;</i>' +
        '                                </button>' +
        '                            </div>' +
        '                        </div>' +
        '                    </div>');

    layui.form.render();
    layui.element.init();

}


/**
 * 删除贝叶斯分类的语料
 * @param formClassName
 * @param node
 */
function deleteBayesInput(formClassName, node) {


    if ($('.' + formClassName).find('.div_bayes_text').length == 1) {
        layer.msg("你删了这最后1个我怎么演示啊？😁");
        return;
    }
    node.parent().parent().parent().remove();
    layui.form.render();
    layui.element.init();
}


/**
 * 提交贝叶斯训练的语料，返回模型的标签
 */
function handonBayesData() {

    //构建json字符串
    var obj = new Object();
    var objData = new Array();
    var nodes = $('.form_bayes').children();
    for (var i = 0; i < nodes.length; i++) {
        var tmpObj = new Object();
        var tmpArr = new Array();
        var typeName = $(nodes[i]).find('input[name=\'typeName\']').val();
        var sample = $(nodes[i]).find('input[name=\'SIMILAR_TEXT\']').val().split("|||");
        for (var j = 0; j < sample.length; j++) {
            var o = new Object();
            o.text = sample[j];
            tmpArr.push(o);
        }
        tmpObj.name = typeName;
        tmpObj.sample = tmpArr;
        objData.push(tmpObj);
    }
    obj.data = objData;
    console.log(obj);
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_bayes_train,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        $('#bayes_res_md5').empty();
        $('#bayes_res_md5').append('训练模型Tag：<i style="color: #A67727;">' + data.data.tag + '</i>');
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });


}


/**
 * 贝叶斯增加预测分类的
 */
function addReadyToClassifyInput(formClassName) {


    var selecter = "." + formClassName;
    if ($(selecter).find('.div_ready_classify_text').length == 5) {
        layer.msg("5个够演示就好啦，别点了");
        return;
    }

    var textGroup = $('.' + formClassName).find('.div_ready_classify_text').parent();

    textGroup.append('  <div class="layui-form-item div_ready_classify_text">' +
        '                                <label class="layui-form-label">待分类文本</label>' +
        '                                <div class="layui-input-inline" style="width: 72%">' +
        '                                    <input type="text" name="TEXT" lay-verify="title"' +
        '                                           autocomplete="off"' +
        '                                           placeholder="输入文本"' +
        '                                           class="layui-input"/>' +
        '                                </div>' +
        '                                <div class="layui-input-inline" style="width: 120px">' +
        '                                    <div class="layui-btn-group">' +
        '                                        <button type=\'button\' id=""' +
        '                                                class="layui-btn layui-btn"' +
        '                                                onclick=\'addReadyToClassifyInput("bayes_inner_classify")\'>' +
        '                                            <i class="layui-icon">&#xe654;</i>' +
        '                                        </button>' +
        '                                        <button type=\'button\' id=""' +
        '                                                class="layui-btn layui-btn-warm layui-btn"' +
        '                                                onclick=\'deleteReadyToClassifyInput("bayes_inner_classify",$(this))\'>' +
        '                                            <i class="layui-icon">&#xe640;</i>' +
        '                                        </button>' +
        '                                    </div>' +
        '                                </div>' +
        '                            </div>');

    layui.form.render();
    layui.element.init();

}


/**
 * 删除贝叶斯等待分类的语料
 * @param formClassName
 * @param node
 */
function deleteReadyToClassifyInput(formClassName, node) {


    if ($('.' + formClassName).find('.div_ready_classify_text').length == 1) {
        layer.msg("你删了这最后1个我怎么演示啊？😁");
        return;
    }
    node.parent().parent().parent().remove();
    layui.form.render();
    layui.element.init();
}


/**
 * 执行贝叶斯分类
 */
function handonClassify() {

    var obj = new Object();
    var texts = new Array();
    var tag = $('#model_tag').val();
    var nodes = $('#div_bayes_inner_classify').children();
    for (var i = 0; i < nodes.length; i++) {
        var text = $(nodes[i]).find('input[name=\'TEXT\']').val();
        var tObj = new Object();
        tObj.text = text;
        texts.push(tObj);
    }

    obj.tag = tag;
    obj.texts = texts;
    var requestJson = JSON.stringify(obj);
    //发送异步请求
    jQuery.ajax({
        url: discourse_emotion_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        console.log(data);
        printRes(data);
        layer.close(layerIndex);
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });


    /**
     * 输出结果
     * @param data
     */
    function printRes(data) {

        var res = data.data.res;
        var legend = data.data.catlog;
        var resStr = "";


        for (var i = 0; i < res.length; i++) {

            resStr += '<fieldset class="layui-elem-field">' +
                '        <legend>结果集合</legend>' +
                '        <div class="layui-field-box">' +
                '                <fieldset class="layui-elem-field layui-field-title">' +
                '                        <legend>原文</legend>' +
                '                        <div class="layui-field-box">' +
                '                                <blockquote class="layui-elem-quote  layui-quote-nm">' + res[i].text + '</blockquote></div>' +
                '                </fieldset>' +
                '                <fieldset class="layui-elem-field layui-field-title">' +
                '                        <legend>分类结果</legend>' +
                '                        <div class="layui-field-box"></div>' +
                '                </fieldset>' +
                '                <div class="layui-row">' +
                '                        <div class="layui-col-md12">' +
                '                                <div class="layui-btn-container">' +
                '                                        <div id="div_tmp_graph_' + i + '" style="width: 900px;height:500px;"></div>' +
                '                                </div>' +
                '                        </div>' +
                '                </div>' +
                '        </div>' +
                '</fieldset>';

        }


        //弹出窗口
        layer.open({
            type: 1,
            title: '结果展示',
            shade: 0,
            maxmin: true,
            skin: 'layui-layer-rim', //加上边框
            area: ['840px', '480px'], //宽高
            content: resStr
        });

        for (var i = 0; i < res.length; i++) {

            var thisChart = null;
            // 基于准备好的dom，初始化ECharts实例
            if (thisChart != null && thisChart != "" && thisChart != undefined) {
                thisChart.dispose();
            }
            thisChart = echarts.init(document.getElementById('div_tmp_graph_' + i), 'macarons');
            thisChart.showLoading();


            var option_raw = {
                title: {
                    text: '贝叶斯分类结果概率图',
                    subtext: '贝叶斯模型',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    x: 'center',
                    y: 'bottom',
                    data: ['rose1', 'rose2', 'rose3', 'rose4', 'rose5', 'rose6', 'rose7', 'rose8']
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: {show: true},
                        dataView: {show: true, readOnly: false},
                        magicType: {
                            show: true,
                            type: ['pie', 'funnel']
                        },
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                calculable: true,
                series: [
                    {
                        name: '概率大小',
                        type: 'pie',
                        radius: [30, 120],
                        center: ['50%', '50%'],
                        roseType: 'radius',
                        data: res[i].classify
                    }
                ]
            };

            thisChart.hideLoading();
            thisChart.setOption(option_raw, true);

        }


    }
}
